package com.yu.mall.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
public class ExcelUtil {

    public static OutputStream getOutputStream(String fileName,HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }

    public static void write(String fileName,List data,String sheetName,List<String> head,HttpServletResponse response) throws Exception {
        OutputStream outputStream = getOutputStream(fileName, response);
        List<List<String>> list = new ArrayList();
        ExcelWriterSheetBuilder sheet = EasyExcel.write(outputStream).sheet(sheetName);
        if(head != null){
            for (String s : head) {
                list.add(Collections.singletonList(s));
            }
            sheet.head(list);
        }
        sheet.doWrite(data);
    }

    public static void write(String fileName,List data,String sheetName,Class clz,HttpServletResponse response) throws Exception {
        OutputStream outputStream = getOutputStream(fileName, response);
        ExcelWriterSheetBuilder sheet = EasyExcel.write(outputStream,clz).sheet(sheetName);
        sheet.doWrite(data);
    }

}
